package org.colin.service.impl;

import java.util.List;
import org.colin.Tools.DateUtil;
import org.colin.Tools.Tool;
import org.colin.constant.Constants;
import org.colin.mapper.SysResourceMapper;
import org.colin.mapper.SysRoleMapper;
import org.colin.model.ro.RoleResourceRO;
import org.colin.model.ro.SysRoleRO;
import org.colin.model.vo.Result;
import org.colin.model.vo.SysResourceVO;
import org.colin.model.vo.SysRoleVO;
import org.colin.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

@Service
public class RoleServiceImpl implements RoleService {

	@Autowired
	private SysRoleMapper sysRoleMapper;

	@Autowired
	private SysResourceMapper sysResourceMapper;

	@Override
	public Result insert(SysRoleRO resource) {
		resource.setId(Tool.getPrimaryKey());
		resource.setCreateTime(DateUtil.getCurrentDate());
		resource.setUpdateTime(DateUtil.getCurrentDate());
		int result = sysRoleMapper.insert(resource);
		if (result == 1) {
			return Result.success();
		} else {
			return Result.fail();
		}
	}

	@Override
	public Result delete(String id) {
		int result = sysRoleMapper.deleteByPrimaryKey(id);
		if (result == 1) {
			return Result.success();
		} else {
			return Result.fail();
		}
	}

	@Override
	public Result<SysRoleVO> selectAll(SysRoleRO resource) {
		List<SysRoleVO> list = sysRoleMapper.selectAll(resource);
		return Result.success(list);
	}

	@Override
	public Result update(SysRoleRO resource) {
		resource.setUpdateTime(DateUtil.getCurrentDate());
		int result = sysRoleMapper.update(resource);
		if (result == 1) {
			return Result.success();
		} else {
			return Result.fail();
		}
	}

	// 修改角色权限
	@Override
	public Result updateRoleResource(RoleResourceRO roleResourceRO) {
		if (Tool.isBlank(roleResourceRO.getRoleId())) {
			return Result.fail(Constants.FAIL_CODE, "角色ID不能为空");
		}
		if (CollectionUtils.isEmpty(roleResourceRO.getResourceIds())) {
			return Result.fail(Constants.FAIL_CODE, "请勾选权限资源");
		}
		// 1.删除角色所有的权限资源
		sysRoleMapper.deleteRoleResource(roleResourceRO.getRoleId());
		// 2.添加角色权限资源
		int result = sysRoleMapper.addRoleResource(roleResourceRO);
		if (result > 0) {
			return Result.success();
		} else {
			return Result.fail();
		}
	}

	// 根据角色ID查询所有资源信息
	@Override
	public Result selectResourceListByRoleId(String roleId) {
		List<SysResourceVO> list = sysResourceMapper.selectResourceByRoleId(roleId);
		return Result.success(list);
	}

}
